package com.css.fxfzdzzh.modules.sandLiquefaction.controller;

import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.modules.eqLandslide.count.param.TaskModelParam;
import com.css.fxfzdzzh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzdzzh.modules.sandLiquefaction.entity.Ahp;
import com.css.fxfzdzzh.modules.sandLiquefaction.param.EvaluateParam;
import com.css.fxfzdzzh.modules.sandLiquefaction.service.SandLiquefactionService;
import com.css.fxfzdzzh.modules.sandLiquefaction.vo.DzzhModelResultVO;
import com.css.fxfzdzzh.modules.sandLiquefaction.vo.DzzhResultSandLiquefactionVO;
import com.css.fxfzdzzh.modules.sandLiquefaction.vo.SandPolygonEvaluateResultVO;
import com.css.fxfzdzzh.util.PlatformPageUtils;
import com.css.fxfzdzzh.util.ResponseCreator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2023年03月11日  11:09
 * 砂土液化
 */
@RestController
@RequestMapping("/sand")
@Validated
public class SandLiquefactionController {

    @Resource
    SandLiquefactionService sandLiquefactionService;
    @Resource
    HypergraphService hypergraphService;

    /** 
     * 任务列表数据分页查询
     */
    @GetMapping("/getTaskPage")
    public RestResponse getTaskPage(HttpServletRequest request, TaskModelParam param){
        int curPage = Integer.parseInt(request.getParameter(PlatformPageUtils.CUR_PAGE));
        int pageSize=Integer.parseInt(request.getParameter(PlatformPageUtils.PAGE_SIZE));
        return ResponseCreator.createSuccessResponse(sandLiquefactionService.getModelSandLiquefaction(param,curPage,pageSize));
    }

    /**
     * 获取最终结果数据
     */
    @GetMapping("/getFinalResult")
    public RestResponse getFinalResult(@NotBlank(message = "任务id不能为空") String taskId,String algorithmType){
        try{
            DzzhModelResultVO finalResult = sandLiquefactionService.getFinalResult(taskId, algorithmType);
            return ResponseCreator.createSuccessResponse(finalResult);
        }catch (Exception ex){
            ex.printStackTrace();
            return ResponseCreator.createFailResponse("查询失败");
        }
    }

    /**
     * 评估详情查看
     */
    @GetMapping("/details")
    public RestResponse details(String dmslId, BigDecimal earthquakeAcceleration,String liquefactionGroundWaterDepth){
        return ResponseCreator.createSuccessResponse(sandLiquefactionService.details(dmslId,earthquakeAcceleration,liquefactionGroundWaterDepth));
    }

    /**
     * 获取层次分析法的最终结果数据
     */
    @GetMapping("/getAhpFinalResult")
    public RestResponse getAhpFinalResult(@NotBlank(message = "任务id不能为空") String taskId) throws IllegalAccessException {
        return ResponseCreator.createSuccessResponse(sandLiquefactionService.getAhpFinalResult(taskId));
    }
    /**
     * 中间结果修改时页面展示的数据
     * taskId 任务id
     * algorithmType 1:标贯法；2：液化指数法；3：层次分析法
     * dmslId 模型id
     */
    @GetMapping("/getCenterResult")
    public RestResponse getCenterResult(String taskId,String algorithmType,String dmslId) throws IllegalAccessException {
        return ResponseCreator.createSuccessResponse(sandLiquefactionService.getCenterResult(taskId,algorithmType,dmslId));
    }

    /**
     * 保存为中间结果
     */
    @PostMapping("/saveToCenterResult")
    public RestResponse saveToCenterResult(@RequestBody Map<String,String> map){
       sandLiquefactionService.saveToCenterResult(map.get("taskId"),map.get("algorithmType"));
       return ResponseCreator.createSuccessResponse("保存中间结果成功");
    }

    /***
     * 中间结果列表查询
     * @param taskId
     * @return
     */
    @GetMapping("/getCenterDataPage")
    public RestResponse getCenterDataPage(String taskId, HttpServletRequest request){
        int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
        int pageSize=Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
        Map<String,Object> page=sandLiquefactionService.getCenterDataPage(taskId,curPage,pageSize);
        return ResponseCreator.createSuccessResponse(page);
    }


    /**
     * 删除中间结果
     */
    @PostMapping("/delCenterResult")
    public RestResponse delCenterResult(@RequestBody Map<String,String> map){
        sandLiquefactionService.delResult(map.get("dmslId"));
        return ResponseCreator.createSuccessResponse("刪除中间结果成功");
    }

    /**
     * 将中间结果替换为最终结果 replaceToFinalResult
     */
    @PostMapping("/saveToFinalResult")
    public RestResponse replaceToFinalResult(@RequestBody Map<String,String> map){
        sandLiquefactionService.replaceToFinalResult(map.get("dmslId"),map.get("flag"),map.get("taskId"));
        return ResponseCreator.createSuccessResponse("替换最终结果成功");
    }



    /**
     * 评估计算 标贯法和液化指数法
     */
    @PostMapping("/evaluate")
    public RestResponse evaluate(@Valid @RequestBody EvaluateParam param){
        try{
            String dmslId = sandLiquefactionService.evaluate(param);
            //刷新指定超图工作空间数据源数据集
            boolean bool = hypergraphService.getWorkspaceReload("dzzh_result_sand_liquefaction");
            return ResponseCreator.createSuccessResponse(dmslId,"评估计算完成");
        }catch (Exception ex){
            return ResponseCreator.createFailResponse("评估计算失败");
        }

    }

    /**
     * 評估計算后获取计算结果列表
     */
    @GetMapping("/getEvaluateResult")
    public RestResponse getEvaluateResult(String dmslId,String taskDistrict,String taskId){
        Long start = System.currentTimeMillis();
        List<DzzhResultSandLiquefactionVO> list = sandLiquefactionService.getEvaluateResult(dmslId,taskDistrict,taskId);
        System.out.println(("时间"+(System.currentTimeMillis()-start)/1000));
        return ResponseCreator.createSuccessResponse(list);
    }


    /**
     * 评估计算 层次分析法
     */
    @PostMapping("/evaluate1")
    public RestResponse evaluate1(@Valid @RequestBody Ahp ahp) throws Exception {
        Long start = System.currentTimeMillis();
        sandLiquefactionService.evaluate1(ahp);
        System.out.println("层次分析法评估计算时间为"+(System.currentTimeMillis()-start)/1000);
        return ResponseCreator.createSuccessResponse("评估计算完成");
    }

    /**
     * 评估计算 层次分析法
     */
    @PostMapping("/handleRiver")
    public RestResponse handleRiver(@Valid @RequestBody Ahp ahp) throws Exception {
        System.out.println("开始处理河流数据");
        Long start = System.currentTimeMillis();
        String fileName = sandLiquefactionService.handleRiver(ahp);
        Long end = System.currentTimeMillis();
        System.out.println("河流数据处理结束，共花费时间"+(end-start)/1000+"秒");
        return ResponseCreator.createSuccessResponse(fileName);
    }


    /**
     * 钻孔数据预处理：转孔数据页面点击选择链接时查询指定钻孔版本的数据缓存到Redis中用于后续的计算
     */
    @PostMapping("/chooseDrillData")
    public RestResponse chooseDrillData(@RequestBody Map<String,String> map){
        return sandLiquefactionService.chooseDrillData(map.get("versionCode"),map.get("taskId"));
    }

    /**
     * 导入钻孔数据
     */
    @PostMapping("/importDrillData/{taskId}/{versionCode}")
    public RestResponse importDrillData(@PathVariable("taskId") String taskId, @PathVariable(value = "versionCode",required = false) String versionCode, @RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
        return sandLiquefactionService.importDrillData(taskId,versionCode, file, response);
    }

    /**
     * 导出标贯法的数据
     */
    @PostMapping("/export")
    public void export(@RequestBody Map<String,Object> map ,HttpServletResponse response){
        String dmslId = (String) map.get("dmslId");
        Double earthquakeAcceleration = (Double)map.get("earthquakeAcceleration");
        Object liquefactionGroundWaterDepth1 = map.get("liquefactionGroundWaterDepth");
        Double liquefactionGroundWaterDepth = 0.0;
        if("实际水位深度".equals(liquefactionGroundWaterDepth1)){
            liquefactionGroundWaterDepth = 1.0;
        }
        String flag = (String) map.get("flag");
        sandLiquefactionService.export(dmslId,earthquakeAcceleration,liquefactionGroundWaterDepth,flag,response);
    }

  /**
   * 更换模型前，请选择是否将当前结果存为中间结果？选择“否”当前结果将被覆盖。
   */
    @PostMapping("/changeModel")
    public void changeModel(@RequestBody Map<String, Object> map) {
        String dmslId = (String) map.get("dmslId");
        String taskId = (String)map.get("taskId");
        String flag = (String) map.get("flag");
        sandLiquefactionService.changeModel(dmslId,taskId,flag);
    }

    /**
     * 批量保存砂土液化区域计算结果
     */
    @PostMapping("/savePolygonEvaluateResult")
    public RestResponse savePolygonEvaluateResult(@RequestBody List<SandPolygonEvaluateResultVO> voList){
        sandLiquefactionService.savePolygonEvaluateResult(voList);
        if (voList.size()>0) {
            //刷新指定超图工作空间数据源数据集
            boolean bool = hypergraphService.getWorkspaceReload("dzzh_sand_liquefaction_polygon_evaluate_result");
        }
        return ResponseCreator.createSuccessResponse("","区域计算成功");
    }

    /**
     * 计算综合地形指数
     * @param teraVersion 高程版本
     */
    @GetMapping("/calculateOmprehensiveTerrainIndex")
    public RestResponse calculateOmprehensiveTerrainIndex(@RequestParam  String teraVersion,@RequestParam  String taskId,@RequestParam  String gcFileName,@RequestParam  String dmslId) throws Exception {
        long start = System.currentTimeMillis();
        Map<String,Object> map = new HashMap<>();
        sandLiquefactionService.calculateOmprehensiveTerrainIndex(teraVersion,taskId,map,gcFileName,dmslId);
        long end = System.currentTimeMillis();
        System.out.println((end-start)/1000);
        return ResponseCreator.createSuccessResponse(map,"综合地形指数计算成功");
    }

    /**
     * 计算场地类别
     * @param  teraVersion 高程版本
     * @Desc 场地类别分为活动构造区和稳定构造区
     */
    @GetMapping("/calculateLandForm")
    public RestResponse calculateSite(@RequestParam  String teraVersion,@RequestParam  String taskId,@RequestParam  String gcFileName,@RequestParam  String dmslId) throws Exception {
        Map<String,Object> map = new HashMap<>();
        sandLiquefactionService.calculateSite(teraVersion,taskId,map,gcFileName,dmslId);
        return ResponseCreator.createSuccessResponse(map,"场地类别计算成功");
    }


    //按省统计危险性面积（【砂土液化-层次分析法】分析评估结果）
    @PostMapping("/countResultAreaByProvince")
    public RestResponse countResultAreaByProvince(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=sandLiquefactionService.countResultAreaByProvince(map.get("taskId"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按省统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按省统计危险性面积失败！");
        }
        return restResponse;
    }

    //按市统计危险性面积（【砂土液化-层次分析法】分析评估结果）
    @PostMapping("/countResultAreaByCity")
    public RestResponse countResultAreaByCity(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=sandLiquefactionService.countResultAreaByCity(map.get("taskId"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按市统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按市统计危险性面积失败！");
        }
        return restResponse;
    }

    //按区县统计危险性面积（【砂土液化-层次分析法】分析评估结果）
    @PostMapping("/countResultAreaByCounty")
    public RestResponse countResultAreaByCounty(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=sandLiquefactionService.countResultAreaByCounty(map.get("taskId"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按市统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按市统计危险性面积失败！");
        }
        return restResponse;
    }

    /**
     * @author Dongbj
     * @date 2023/10/10 10:04
     * @param taskId 任务id
     * @param type 1:综合地形指数  2：场地类别-活动构造区 3：场地类别-稳定构造区
     * @return RestResponse
     * @desc
     */
    @GetMapping("/getMapResultFile")
    public RestResponse getMapResultFile(@RequestParam String taskId,@RequestParam String type,@RequestParam String dmslId) throws Exception{
        return ResponseCreator.createSuccessResponse(sandLiquefactionService.getMapResultFile(taskId,type,dmslId));
    }


    /**
     * @author Dongbj
     * @date 2023/10/31 11:23
     * @param taskId 任务id
     * @param dmslId 模型id
     * @param landform 场地类别
     * @param pga 地动峰加速度
     * @return null
     * @desc
     */
    @GetMapping("/getFinalMapResultFile")
    public RestResponse getFinalMapResultFile(@RequestParam String taskId,@RequestParam String dmslId,
                                              @RequestParam String landform,@RequestParam String pga){
        return ResponseCreator.createSuccessResponse(sandLiquefactionService.getFinalMapResultFile(taskId,dmslId,landform,pga));
    }

    /**
     * 基础数据水系版本发生替换时 远程调用该接口删除地质灾害中count_buffer中的水系数据
     */
    @PostMapping("/deleteCountBuffer")
    public RestResponse deleteCountBuffer(){
        sandLiquefactionService.deleteCountBuffer();
        return ResponseCreator.createSuccessResponse("删除水系数据成功");
    }
}
